package sample.jasperreport.service;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.data.JsonDataSource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import sample.jasperreport.dto.StudentDto;
import sample.jasperreport.mapper.StudentMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : dongyz8
 * @Date : 2023/11/3 18:24
 **/
@Service
public class JasperServiceImpl implements JasperService{

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public byte[] toPDF(HttpServletResponse response){
        try {
//            JasperPrint jasperPrint = getDataSourceByJsonFile();

            JasperPrint jasperPrint = getDataSourceByJavaBean();

            return JasperExportManager.exportReportToPdf(jasperPrint);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 通过JSON文件获取数据源
     * @return
     * @throws Exception
     */
    private JasperPrint getDataSourceByJsonFile() throws Exception{
        JRDataSource dataSource = new JsonDataSource(resourceLoader
                .getResource("classpath:json/data.json").getFile());

        //读取报表模板
        String path = resourceLoader
                .getResource("classpath:jasper/3.jrxml").getURL().getPath();
        JasperReport jasperReport = JasperCompileManager
                .compileReport(path);

        //需要传给报表的参数
        Map<String, Object> parameters = new HashMap<>();
//            parameters.put("paramName", paramValue);
        return JasperFillManager.fillReport(jasperReport, parameters, dataSource);

    }

    /**
     * 通过数据库获取数据源
     */
    private JasperPrint getDataSourceByJavaBean() throws Exception{
        List<StudentDto> studentDtoList = studentMapper.queryByParam(new HashMap<>());
        JRDataSource dataSource = new JRBeanCollectionDataSource(studentDtoList);

        //读取报表模板
        String path = resourceLoader
                .getResource("classpath:jasper/4.jrxml").getURL().getPath();
        JasperReport jasperReport = JasperCompileManager
                .compileReport(path);

        //需要传给报表的参数
        Map<String, Object> parameters = new HashMap<>();
//            parameters.put("paramName", paramValue);
        return JasperFillManager.fillReport(jasperReport, parameters, dataSource);
    }
}
